package edu.ynu.se.xiecheng.achitectureclass.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.UUID;

@Slf4j
@Component
public class OssUtils {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String uploadToOSS(byte[] imageBytes, String deviceSerial) {
        String objectName = String.format("camera-images/%s/%s.jpg", deviceSerial, UUID.randomUUID());
        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            // 上传图片到OSS
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(imageBytes));
            
            // 返回可访问的URL
            return String.format("https://%s.%s/%s", bucketName, endpoint, objectName);
        } catch (Exception e) {
            log.error("上传图片到OSS失败: {}", e.getMessage(), e);
            throw new RuntimeException("上传图片到OSS失败", e);
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
